package com.osce.basic.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.csce.domain.entity.basic.TabAssetInventory;
import com.csce.domain.entity.basic.TabAssetInventoryConsumable;
import com.csce.domain.entity.basic.vo.TabAssetInventoryConsumableExcel;
import com.csce.domain.entity.basic.vo.TabAssetInventoryExcel;
import com.osce.interfaces.basic.ITabAssetInventoryConsumableService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.osce.common.annotation.Log;
import com.osce.common.core.controller.BaseController;
import com.osce.common.core.entity.AjaxResult;
import com.osce.common.enums.BusinessType;
import com.osce.common.utils.poi.ExcelUtil;
import com.osce.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 资产耗材Controller
 *
 * @author hdj
 * @since 2025-11-15
 */
@RestController
@RequestMapping("/basic/consumable")
public class TabAssetInventoryConsumableController extends BaseController {

    @Resource
    private ITabAssetInventoryConsumableService tabAssetInventoryConsumableService;

    /**
     * 查询资产耗材列表
     */
    @PreAuthorize("@ss.hasPermi('basic:consumable:list')")
    @GetMapping("/list")
    public TableDataInfo list(TabAssetInventoryConsumable tabAssetInventoryConsumable) {
        startPage();
        List<TabAssetInventoryConsumable> list = tabAssetInventoryConsumableService.selectTabAssetInventoryConsumableList(tabAssetInventoryConsumable);
        return getDataTable(list);
    }

    /**
     * 查询资产耗材库存预警列表
     */
    @PreAuthorize("@ss.hasPermi('basic:consumable:list')")
    @GetMapping("/list/alert")
    public AjaxResult listAlert(TabAssetInventoryConsumable tabAssetInventoryConsumable) {
        List<TabAssetInventoryConsumable> list = tabAssetInventoryConsumableService.selectTabAssetInventoryConsumableList(tabAssetInventoryConsumable);

        // 筛选出需要预警的耗材资产列表
        // 第一个过滤条件：筛选出数量和预警数量都不为空且预警数量大于0的资产
        List<TabAssetInventoryConsumable> collect = list.stream()
                .filter(asset -> {
                    Long number = asset.getNumber();
                    Long warningNumber = asset.getWarningNumber();
                    return number != null && warningNumber != null && warningNumber > 0;
                })
                // 第二个过滤条件：筛选出当前数量小于预警数量50%的资产（即库存严重不足的资产）
                .filter(asset -> {
                    Long number = asset.getNumber();
                    Long warningNumber = asset.getWarningNumber();
                    return number < warningNumber * 0.5;
                })
                .collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    /**
     * 导出资产耗材列表
     */
    @PreAuthorize("@ss.hasPermi('basic:consumable:export')")
    @Log(title = "资产耗材", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TabAssetInventoryConsumable tabAssetInventoryConsumable) {
        List<TabAssetInventoryConsumable> list = tabAssetInventoryConsumableService.selectTabAssetInventoryConsumableList(tabAssetInventoryConsumable);
        ExcelUtil<TabAssetInventoryConsumable> util = new ExcelUtil<TabAssetInventoryConsumable>(TabAssetInventoryConsumable. class);
        util.exportExcel(response, list, "资产耗材数据");
    }

    /**
     * 导出耗材模板
     */
    @PostMapping("/importTemplate")
    @PreAuthorize("@ss.hasPermi('basic:consumable:import')")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<TabAssetInventoryConsumableExcel> util = new ExcelUtil<>(TabAssetInventoryConsumableExcel.class);
        util.importTemplateExcel(response, "耗材数据");
    }

    /**
     * 导入固定资产管理列表
     */
    @Log(title = "导入耗材管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('basic:consumable:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) {
        try {
            ExcelUtil<TabAssetInventoryConsumable> util = new ExcelUtil<TabAssetInventoryConsumable>(TabAssetInventoryConsumable.class);
            List<TabAssetInventoryConsumable> tabAssetInventoryConsumableList = util.importExcel(file.getInputStream());

            // 调用service层导入数据，此时即使部分数据失败，也会继续处理并返回完整结果
            String message = tabAssetInventoryConsumableService.importTabAssetInventoryConsumable(tabAssetInventoryConsumableList);

            // 返回成功消息，包含导入结果详情
            return AjaxResult.success(message);
        } catch (Exception e) {
            // 捕获解析文件等非业务异常
            return AjaxResult.error("导入耗材数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取资产耗材详细信息
     */
    @PreAuthorize("@ss.hasPermi('basic:consumable:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tabAssetInventoryConsumableService.selectTabAssetInventoryConsumableById(id));
    }

    /**
     * 新增资产耗材
     */
    @PreAuthorize("@ss.hasPermi('basic:consumable:add')")
    @Log(title = "资产耗材", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TabAssetInventoryConsumable tabAssetInventoryConsumable) {
        return toAjax(tabAssetInventoryConsumableService.insertTabAssetInventoryConsumable(tabAssetInventoryConsumable));
    }

    /**
     * 修改资产耗材
     */
    @PreAuthorize("@ss.hasPermi('basic:consumable:edit')")
    @Log(title = "资产耗材", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TabAssetInventoryConsumable tabAssetInventoryConsumable) {
        return toAjax(tabAssetInventoryConsumableService.updateTabAssetInventoryConsumable(tabAssetInventoryConsumable));
    }

    /**
     * 删除资产耗材
     */
    @PreAuthorize("@ss.hasPermi('basic:consumable:remove')")
    @Log(title = "资产耗材", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tabAssetInventoryConsumableService.deleteTabAssetInventoryConsumableByIds(ids));
    }
}
